<script setup>
import { ref } from 'vue'
import ChannelSelect from '@/views/article/component/ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  addArticleServer,
  getArticleDetailServer,
  updateArticleDetailServer
} from '@/api/article.js'
import { baseURL } from '@/utils/request.js'
import axios from 'axios'
const dialog = ref(false)
const title = ref('')
const article = ref(null)
const articleForm = ref({
  id: '',
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})
// 显示的图片
const imageUrl = ref('')
const rules = ref({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 30, message: '文章标题必须是1-30位的字符', trigger: 'blur' }
  ],
  cate_id: { required: true, message: '请选择文章分类', trigger: 'change' },
  cover_img: { required: true, message: '请选择文章封面', trigger: 'change' },
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '<p><br></p>') {
          callback(new Error('请输入文章内容'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
const open = async row => {
  if (!row.id) {
    title.value = '发布文章'
  } else {
    title.value = '编辑文章'
    const res = await getArticleDetailServer(row.id)
    articleForm.value = res.data
    imageUrl.value = baseURL + articleForm.value.cover_img
    articleForm.value.cover_img = await imageUrlToFile(
      imageUrl.value,
      articleForm.value.cover_img
    )
  }
  dialog.value = true
}
defineExpose({ open })

// 图片上传
const onUploadFile = uploadFile => {
  // 创建图片路径--只是为了页面能展示图片
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  // uploadFile.raw是文件本体
  articleForm.value.cover_img = uploadFile.raw
  article.value.validateField('cover_img')
}

// 富文本编辑器失去焦点时再次验证一次内容
const testContent = () => {
  article.value.validateField('content')
}
// 发布
const emit = defineEmits(['success'])
const submitArticle = async key => {
  articleForm.value.state = key
  article.value.validate()
  const fd = new FormData()
  for (const key in articleForm.value) {
    fd.append(key, articleForm.value[key])
  }
  if (!articleForm.value.id) {
    await addArticleServer(fd)
    ElMessage.success('发布成功')
    emit('success', 'add')
  } else {
    // 接口需要的是 FormData 的数据
    await updateArticleDetailServer(fd)
    ElMessage.success('修改成功')
    emit('success', 'edit')
  }
  handleClose()
}
// 抽屉关闭时运行
const handleClose = () => {
  article.value.resetFields()
  imageUrl.value = ''
  articleForm.value.content = '<p></p>'
  dialog.value = false
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
</script>

<template>
  <el-drawer
    v-model="dialog"
    :title="title"
    :before-close="handleClose"
    direction="rtl"
    class="demo-drawer"
    size="50%"
  >
    <div class="demo-drawer__content">
      <!--      这里的 ref="article" 不要和其他属性同名,不然会出现表单无法填写的故障-->
      <el-form :model="articleForm" :rules="rules" ref="article">
        <el-form-item label="id" :label-width="120" style="display: none">
          <el-input v-model="articleForm.id" autocomplete="off" />
        </el-form-item>
        <el-form-item label="文章标题: " :label-width="100" prop="title">
          <el-input v-model="articleForm.title" autocomplete="off" />
        </el-form-item>
        <!--文章分类开始-->
        <el-form-item label="文章分类：" :label-width="100" prop="cate_id">
          <channel-select v-model="articleForm.cate_id"></channel-select>
        </el-form-item>
        <!--文章分类结束-->
        <el-form-item label="文章封面：" :label-width="100" prop="cover_img">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="onUploadFile"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容：" :label-width="100" prop="content">
          <div class="editor">
            <QuillEditor
              v-model:content="articleForm.content"
              contentType="html"
              theme="snow"
              @blur="testContent"
            />
          </div>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer" style="margin: 50px 100px">
        <el-button type="primary" @click="submitArticle('已发布')"
          >发布</el-button
        >
        <el-button type="info" @click="submitArticle('草稿')">草稿</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
